package com.example.backend.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.backend.api.common.Result;
import com.example.backend.api.entity.Absence;
import com.example.backend.api.mapper.AbsenceMapper;
import com.example.backend.api.service.AbsenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwyzsn
 * @since 2023-03-07
 */
@Service
public class AbsenceServiceImpl extends ServiceImpl<AbsenceMapper, Absence> implements AbsenceService {

    @Autowired
    private AbsenceMapper absenceMapper;

    public Result getAll() {
        QueryWrapper<Absence> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("status");
        return  Result.success(absenceMapper.selectList(queryWrapper));
    }

    public Result approve(Integer id, String status) {
        UpdateWrapper<Absence> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", id);
        updateWrapper.set("status", status);
        absenceMapper.update(null, updateWrapper);
        return Result.success(null);
    }

    public Result add(Integer id, String reason, String startTime, String endTime,String type,Integer deptId,String name) throws ParseException {
            // convert startTime and endTime to Date
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
            Absence absence = new Absence();
            absence.setUserId(id);
            absence.setReason(reason);
            absence.setType(type);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.setTimeZone(timeZone);
            // get Now time
            Date now = new Date();
            Date startTimeDate =   simpleDateFormat.parse(startTime);
            Date endTimeDate = simpleDateFormat.parse(endTime);
            absence.setStartTime(startTimeDate);
            absence.setEndTime(endTimeDate);
            absence.setApplyTime(now);
            absence.setDeptId(deptId);
            absence.setUsername(name);
            absence.setStatus("0");
            absenceMapper.insert(absence);
            return Result.success(null);

    }

    public Result person(Integer id) {
        QueryWrapper<Absence> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        return Result.success(absenceMapper.selectList(queryWrapper));
    }
}
